package com.qiaofei.controller.api;

import com.qiaofei.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api")
public class UploadController {

    //本地存储文件
    @PostMapping("/upload")
    public Result upload(String type, MultipartFile image) throws Exception {
        if(type == null) type = "upload";
        log.info("文件上传: {}, {}", type, image);
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();

        //构造唯一的文件名 (不能重复) - uuid(通用唯一识别码) de49685b-61c0-4b11-80fa-c71e95924018
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFileName = UUID.randomUUID().toString() + extname;

        //将文件存储在服务器的磁盘目录中
        String parentDir = "static/";
        String path = ResourceUtils.getURL("classpath:").getPath();
        File upload = new File(path, parentDir+type+"/");
        if(!upload.exists()) upload.mkdirs();

        File file = new File(upload.getAbsolutePath()+ "/" + newFileName);
        log.info("新的文件名: {}", parentDir+type+"/"+newFileName);
        image.transferTo(file);
        return Result.success(newFileName);
    }

    /*@PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传, 文件名: {}", image.getOriginalFilename());

        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(image);
        log.info("文件上传完成,文件访问的url: {}", url);

        return Result.success(url);
    }*/

}
